package com.dtagri.fjwlw.ui;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.LayoutParams;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import com.dtagri.fjwlw.AppContext;
import com.dtagri.fjwlw.R;
import com.dtagri.fjwlw.base.BaseSimpleActivity;
import com.dtagri.fjwlw.base.TGson;
import com.dtagri.fjwlw.bean.SmallArea;
import com.dtagri.fjwlw.bean.TjAreaMsg;
import com.dtagri.fjwlw.bean.TjEquipment;
import com.dtagri.fjwlw.bean.UserOperate;
import com.dtagri.fjwlw.fragment.IndexContrastFragment;
import com.dtagri.fjwlw.util.TDevice;
import com.dtagri.fjwlw.util.TToast;
import com.dtagri.fjwlw.widget.EmptyLayout;

/**
 * 指标对比
 * 
 * @author wxjn
 * 
 */
public class IndexContrastActivity extends BaseSimpleActivity {

	public TextView actionbarTitle;

	public Spinner spinner0;
	public Spinner spinner1;
	private TextView chartNum;

	protected List<TjAreaMsg> tjAreaMsgs = new ArrayList<TjAreaMsg>();

	private ArrayList<String> datas0 = new ArrayList<String>();
	private ArrayList<String> datas1 = new ArrayList<String>();

	public SpinnerAdapter spinnerAdapter0 = new SpinnerAdapter(this, datas0);
	public SpinnerAdapter spinnerAdapter1 = new SpinnerAdapter(this, datas1);

	private IndexContrastFragment fragment;

	protected UserOperate userOperate = new UserOperate();

	@Override
	public void onClick(View arg0) {
		int id = arg0.getId();
		switch (id) {
		case R.id.tv_chart_num:
			showCheckDialog();
			break;
		}
	}

	@Override
	public void initView() {
		super.initView();
		mErrorLayout.setErrorType(EmptyLayout.NODATA);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		initTitle();

		initSpinner();
	}

	/**
	 * 初始化标题
	 */
	private void initTitle() {
		View view = getLayoutInflater().inflate(
				R.layout.actionbar_custom_indexcontrasttitle, null);
		actionbarTitle = (TextView) view.findViewById(R.id.tv_actionbar_title);
		actionbarTitle.setText("指标对比");
		mActionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
		LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);
		mActionBar.setCustomView(view, params);

		View back = view.findViewById(R.id.btn_back);
		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				TDevice.hideSoftKeyboard(getCurrentFocus());
				onBackPressed();
			}
		});
	}

	/**
	 * 准备下拉框
	 */
	private void initSpinner() {
		spinner0 = (Spinner) findViewById(R.id.spinner0);
		spinner1 = (Spinner) findViewById(R.id.spinner1);
		chartNum = (TextView) findViewById(R.id.tv_chart_num);
		chartNum.setOnClickListener(this);
		spinner0.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				if (arg2 != userOperate.getSpinnerSelected0()) {
					userOperate.setSpinnerSelected0(arg2);
					userOperate.setSpinnerSelected1(0);
					userOperate.setSpinnerSelected2(0);
					convertData();
					fragment.requestData();
					setAdapters();
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});
		spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				if (arg2 != userOperate.getSpinnerSelected1()) {
					userOperate.setSpinnerSelected1(arg2);
					userOperate.setSpinnerSelected2(0);
					convertData();
					fragment.requestData();
					setAdapters();
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});
		spinner0.setAdapter(spinnerAdapter0);
		spinner1.setAdapter(spinnerAdapter1);
	}

	/**
	 * 更新下拉数据
	 * 
	 */
	private void setAdapters() {
		spinnerAdapter0.setSelectIndex(userOperate.getSpinnerSelected0());
		spinnerAdapter1.setSelectIndex(userOperate.getSpinnerSelected1());
		spinner0.setSelection(userOperate.getSpinnerSelected0(), false);
		spinner1.setSelection(userOperate.getSpinnerSelected1(), false);
		spinnerAdapter0.notifyDataSetChanged();
		spinnerAdapter1.notifyDataSetChanged();
	}

	/**
	 * 数据格式转换
	 */
	private void convertData() {
		datas0.clear();
		for (TjAreaMsg tjAreaMsg : tjAreaMsgs) {
			datas0.add(tjAreaMsg.getAreaName());
		}

		datas1.clear();
		List<TjEquipment> tjEquipments = curBigArea().getTjEquipments();
		for (TjEquipment tjEquipment : tjEquipments) {
			datas1.add(tjEquipment.getEquipName());
		}
	}

	@Override
	public void initData() {
		tjAreaMsgs = rebuildData(AppContext.tjAreaMsgs);
		convertData();
		setAdapters();
		hideWaitDialog();

		fragment.requestData();
		List<Integer> smallAreaIDs =smallAreaIDs();
		Integer integer = smallAreaIDs.get(0);
		List<SmallArea> smallAreas=curEquipment().getSmallAreas();
		String smallName=null;
		for (SmallArea smallArea : smallAreas) {
			if (smallArea.getAreaId() == integer) {
				smallName = smallArea.getSmallName();
			}
		}
		chartNum.setText(smallName);
//		System.out.println("小区名--------------"+smallName);
	}

	public class SpinnerAdapter extends BaseAdapter {

		private final List<String> teams;

		private final Context context;

		private int selectIndex = 0;

		public void setSelectIndex(int index) {
			this.selectIndex = index;
		}

		public SpinnerAdapter(Context context, List<String> teams) {
			this.teams = teams;
			this.context = context;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = LayoutInflater.from(context).inflate(
						R.layout.spinner_layout_head, null);
			}
			((TextView) convertView).setText(getItem(position));

			return convertView;
		}

		@Override
		public View getDropDownView(int position, View convertView,
				ViewGroup parent) {
			if (convertView == null) {
				convertView = LayoutInflater.from(context).inflate(
						R.layout.list_cell_team, null, false);
			}
			String team = getItem(position);
			TextView tv = (TextView) convertView.findViewById(R.id.tv_name);
			if (team != null) {
				tv.setText(team);
			}
			if (selectIndex != position) {
				tv.setTextColor(Color.parseColor("#acd4b3"));
			} else {
				tv.setTextColor(Color.parseColor("#6baf77"));
			}
			return convertView;
		}

		@Override
		public int getCount() {
			return teams.size();
		}

		@Override
		public String getItem(int position) {
			return teams.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

	}

	@Override
	protected Fragment getFragment() {
		fragment = new IndexContrastFragment();
		fragment.setBaseSimpleActivity((BaseSimpleActivity) this);
		return fragment;
	}

	// ===========================================
	/**
	 * 获得当前的传感器
	 * 
	 * @return
	 */
	public TjEquipment curEquipment() {
		List<TjEquipment> tjEquipments = curBigArea().getTjEquipments();
		TjEquipment tjEquipment = tjEquipments.get(userOperate
				.getSpinnerSelected1());
		return tjEquipment;
	}

	/**
	 * 获得勾选小区的id
	 * 
	 * @return
	 */
	public List<Integer> smallAreaIDs() {
		TjEquipment res = curEquipment();
		List<SmallArea> smallAreas = res.getSmallAreas();
		List<Integer> ids = new ArrayList<Integer>();
		for (SmallArea smallArea : smallAreas) {
			if (smallArea.isChecked()) {
				ids.add(smallArea.getAreaId());
			}
		}
		return ids;
	}

	/**
	 * 获得当前大区
	 * 
	 * @return
	 */
	public TjAreaMsg curBigArea() {
		TjAreaMsg tjAreaMsg = tjAreaMsgs.get(userOperate.getSpinnerSelected0());
		return tjAreaMsg;
	}

	/**
	 * 修改数据结构
	 * 
	 * 大区－小区－传感器＝＝〉大区－传感器－小区
	 * 
	 * @param tjAreaMsgs2
	 * @return
	 */
	private List<TjAreaMsg> rebuildData(List<TjAreaMsg> tjAreaMsgs) {
		List<TjAreaMsg> arrayList = new ArrayList<TjAreaMsg>();
		for (TjAreaMsg tjAreaMsg : tjAreaMsgs) {
			List<SmallArea> smallAreas = tjAreaMsg.getSmallAreas();
			List<TjEquipment> newTjEquipments = new ArrayList<TjEquipment>();
			for (SmallArea smallArea : smallAreas) {
				List<TjEquipment> tjEquipments = smallArea.getTjEquipments();
				for (TjEquipment tjEquipment : tjEquipments) {
					// 查找是否存在传感器及下标
					int position = -1;
					for (int i = 0; i < newTjEquipments.size(); i++) {
						TjEquipment newTjEquipment = newTjEquipments.get(i);
						if (newTjEquipment.equals(tjEquipment)) {
							position = i;
							break;
						}
					}

					if (position == -1) {// 不存在传感器，增加一个传感器
						String json = TGson.gson.toJson(tjEquipment);
						TjEquipment copyTjEquipment = TGson.gson.fromJson(json,
								TjEquipment.class);
						String json2 = TGson.gson.toJson(smallArea);
						SmallArea copySmallArea = TGson.gson.fromJson(json2,
								SmallArea.class);

						copySmallArea.setChecked(true);
						copyTjEquipment.getSmallAreas().add(copySmallArea);
						newTjEquipments.add(copyTjEquipment);
					} else {// 存在传感器，传感器下再增加一个小区
						newTjEquipments.get(position).getSmallAreas()
								.add(smallArea);
					}
				}
			}
			tjAreaMsg.setTjEquipments(newTjEquipments);
			arrayList.add(tjAreaMsg);
		}
		return arrayList;
	}

	/**
	 * 勾选小区对话框
	 */
	private void showCheckDialog() {
		List<SmallArea> smallAreas = curEquipment().getSmallAreas();
		final ZCheckAreaDialog dlg = new ZCheckAreaDialog(this, smallAreas);
		dlg.setPositiveButton("确定",
				new android.content.DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						int checkCount = checkCount(dlg.getSmallAreas());
						if (checkCount == 0) {
							TToast.showToastShort("至少选择一个小区");
						} else {
							TjEquipment tjEquipment = tjAreaMsgs
									.get(userOperate.getSpinnerSelected0())
									.getTjEquipments()
									.get(userOperate.getSpinnerSelected1());
							tjEquipment.setSmallAreas(dlg.getSmallAreas());

							chartNum.setText(dlg.getSmallAreas().get(0).getSmallName());
							dlg.dismiss();
							fragment.requestData();
						}

					}
				});
		dlg.show();
	}

	/**
	 * 统计选中条数
	 * 
	 * @param smallAreas
	 * @return
	 */
	protected int checkCount(List<SmallArea> smallAreas) {
		int i = 0;
		for (SmallArea smallArea : smallAreas) {
			if (smallArea.isChecked()) {
				i++;
			}
		}
		return i;
	}
}
